package com.bicycle.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bicycle.common.entity.base.DataGrid;
import com.bicycle.common.entity.base.Message;
import com.bicycle.common.enums.HasDelEnum;
import com.bicycle.common.enums.PermissionBusinessCodeEnum;
import com.bicycle.common.enums.SysUserStatusEnum;
import com.bicycle.service.dto.BicycleSystemUserDto;
import com.bicycle.service.dto.BicycleSystemUserGridDto;
import com.bicycle.service.dto.BicycleSystemUserPasswordDto;
import com.bicycle.service.vo.BicycleSystemUserVo;
import com.bicycle.platform.service.BicycleSystemUserService;

import com.bicycle.service.entity.BicycleSystemRole;
import com.bicycle.service.entity.BicycleSystemUser;
import com.bicycle.service.entity.BicycleSystemUserRole;
import com.bicycle.service.mapper.BicycleSystemRoleMapper;
import com.bicycle.service.mapper.BicycleSystemUserMapper;
import com.bicycle.service.mapper.BicycleSystemUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("userService")
@Transactional(rollbackFor = Exception.class)
public class BicycleSystemUserServiceImpl implements BicycleSystemUserService {

    @Autowired
    private BicycleSystemUserMapper systemUserMapper;
    @Autowired
    private BicycleSystemRoleMapper systemRoleMapper;
    @Autowired
    private BicycleSystemUserRoleMapper systemUserRoleMapper;

    /**
     * 插入系统用户信息
     *
     * @param bicycleSystemUserDto
     * @return
     */
    @Override
    public Message insertSysUser(BicycleSystemUserDto bicycleSystemUserDto) {
        Message message = new Message();

        BicycleSystemUser qBicycleSystemUser = new BicycleSystemUser();
        qBicycleSystemUser.setAccount(bicycleSystemUserDto.getAccount());
        qBicycleSystemUser.setHasDel(HasDelEnum.HAS_DEL_FALSE.getKey());
        BicycleSystemUser systemUser = systemUserMapper.selectOne(new QueryWrapper<BicycleSystemUser>(qBicycleSystemUser));
        ;
        // 账户已存在
        if (systemUser != null) {
            message.setCode(PermissionBusinessCodeEnum.CODE_INFO_ACCOUNT_ALREADY_EXISTS.getKey());
            message.setMessage(PermissionBusinessCodeEnum.CODE_INFO_ACCOUNT_ALREADY_EXISTS.getValue());
            return message;
        }
        BicycleSystemUser bicycleSystemUser = new BicycleSystemUser();
        BeanUtil.copyProperties(bicycleSystemUserDto, bicycleSystemUser);
        BicycleSystemRole bicycleSystemRole = systemRoleMapper.selectById(bicycleSystemUserDto.getRoleId());

        bicycleSystemUser.setRegionId(bicycleSystemRole.getRegionId());
        bicycleSystemUser.setRegionName(bicycleSystemRole.getRegionName());
        bicycleSystemUser.setUserType(bicycleSystemRole.getRoleType());
        bicycleSystemUser.setCreateTime(new Date());
        bicycleSystemUser.setUserStatus(SysUserStatusEnum.USER_STATUS_NORMAL.getKey());
        bicycleSystemUser.setHasDel(HasDelEnum.HAS_DEL_FALSE.getKey());
        // 插入用户基础信息
        systemUserMapper.insert(bicycleSystemUser);
        Integer sysUserId = bicycleSystemUser.getSysUserId();

        BicycleSystemUserRole bicycleSystemUserRole = new BicycleSystemUserRole();
        bicycleSystemUserRole.setSysUserId(sysUserId);
        bicycleSystemUserRole.setRoleId(bicycleSystemUserDto.getRoleId());
        bicycleSystemUserRole.setCreateTime(new Date());
        bicycleSystemUserRole.setCreateBy(bicycleSystemUserDto.getCreateBy());
        bicycleSystemUserRole.setCreateName(bicycleSystemUserDto.getCreateName());
        // 插入用户角色关联信息
        systemUserRoleMapper.insert(bicycleSystemUserRole);

        return message;
    }

    /**
     * 修改系统用户信息
     *
     * @param bicycleSystemUserDto
     * @return
     */
    @Override
    public Message updateSysUser(BicycleSystemUserDto bicycleSystemUserDto) {
        Message message = new Message();
        // 账户名称有变动
        if (StringUtils.isNotBlank(bicycleSystemUserDto.getAccount())) {
            BicycleSystemUser qBicycleSystemUser = new BicycleSystemUser();
            qBicycleSystemUser.setAccount(bicycleSystemUserDto.getAccount());
            qBicycleSystemUser.setHasDel(HasDelEnum.HAS_DEL_FALSE.getKey());
            BicycleSystemUser systemUser = systemUserMapper.selectOne(new QueryWrapper<BicycleSystemUser>(qBicycleSystemUser));
            // 账户已存在
            if (systemUser != null && systemUser.getSysUserId().intValue() != bicycleSystemUserDto.getSysUserId()) {
                message.setCode(PermissionBusinessCodeEnum.CODE_INFO_ACCOUNT_ALREADY_EXISTS.getKey());
                message.setMessage(PermissionBusinessCodeEnum.CODE_INFO_ACCOUNT_ALREADY_EXISTS.getValue());
                return message;
            }
        }

        BicycleSystemUser bicycleSystemUser = systemUserMapper.selectById(bicycleSystemUserDto.getSysUserId());
        BeanUtil.copyProperties(bicycleSystemUserDto, bicycleSystemUser);
        bicycleSystemUser.setUpdateTime(new Date());
        // 角色信息有变动
        if (bicycleSystemUserDto.getRoleId() != null) {
            // 清除用户之前关联
            BicycleSystemUserRole dBicycleSystemUserRole = new BicycleSystemUserRole();
            dBicycleSystemUserRole.setSysUserId(bicycleSystemUserDto.getSysUserId());
            systemUserRoleMapper.delete(new QueryWrapper<BicycleSystemUserRole>(dBicycleSystemUserRole));

            BicycleSystemUserRole bicycleSystemUserRole = new BicycleSystemUserRole();
            bicycleSystemUserRole.setSysUserId(bicycleSystemUserDto.getSysUserId());
            bicycleSystemUserRole.setRoleId(bicycleSystemUserDto.getRoleId());
            bicycleSystemUserRole.setCreateTime(new Date());
            bicycleSystemUserRole.setCreateBy(bicycleSystemUserDto.getCreateBy());
            bicycleSystemUserRole.setCreateName(bicycleSystemUserDto.getCreateName());
            // 插入用户角色关联信息
            systemUserRoleMapper.insert(bicycleSystemUserRole);

            BicycleSystemRole bicycleSystemRole = systemRoleMapper.selectById(bicycleSystemUserDto.getRoleId());
            bicycleSystemUser.setRegionId(bicycleSystemRole.getRegionId());
            bicycleSystemUser.setRegionName(bicycleSystemRole.getRegionName());
            bicycleSystemUser.setUserType(bicycleSystemRole.getRoleType());
        }
        BicycleSystemUser qBicycleSystemUser = new BicycleSystemUser();
        qBicycleSystemUser.setSysUserId(bicycleSystemUser.getSysUserId());
        systemUserMapper.update(bicycleSystemUser, new QueryWrapper<BicycleSystemUser>(qBicycleSystemUser));
        return message;
    }

    /**
     * 分页查询系统用户
     *
     * @param bicycleSystemUserGridDto
     * @return
     */
    @Override
    public DataGrid querySystemUserByPage(BicycleSystemUserGridDto bicycleSystemUserGridDto) {
        DataGrid dataGrid = new DataGrid();

        BicycleSystemUser bicycleSystemUser = new BicycleSystemUser();
        QueryWrapper<BicycleSystemUser> queryWrapper = new QueryWrapper<BicycleSystemUser>(bicycleSystemUser);
        BeanUtil.copyProperties(bicycleSystemUserGridDto, bicycleSystemUser);
        List<BicycleSystemUserVo> bicycleSystemUserVoList = new ArrayList<>();
        if (StringUtils.isNotBlank(bicycleSystemUserGridDto.getAccount())) {
            queryWrapper.like("account", bicycleSystemUserGridDto.getAccount());
            bicycleSystemUser.setAccount(null);
        }
        if (StringUtils.isNotBlank(bicycleSystemUserGridDto.getUserName())) {
            queryWrapper.like("user_name", bicycleSystemUserGridDto.getUserName());
            bicycleSystemUser.setUserName(null);
        }
        if (StringUtils.isNotBlank(bicycleSystemUserGridDto.getMobile())) {
            queryWrapper.like("mobile", bicycleSystemUserGridDto.getMobile());
            bicycleSystemUser.setMobile(null);
        }
        if (StringUtils.isNotBlank(bicycleSystemUserGridDto.getDepartment())) {
            queryWrapper.like("department", bicycleSystemUserGridDto.getDepartment());
            bicycleSystemUser.setDepartment(null);
        }
        bicycleSystemUser.setHasDel(HasDelEnum.HAS_DEL_FALSE.getKey());
        queryWrapper.orderByDesc("create_time");
        IPage<BicycleSystemUser> systemUserIPage = systemUserMapper.selectPage(new Page<BicycleSystemUser>(bicycleSystemUserGridDto.getPage(), bicycleSystemUserGridDto.getRows()), queryWrapper);
        List<BicycleSystemUser> bicycleSystemRoleList = systemUserIPage.getRecords();
        bicycleSystemRoleList.forEach(systemUser -> {
            BicycleSystemUserVo bicycleSystemUserVo = new BicycleSystemUserVo();
            BicycleSystemUserRole bicycleSystemUserRole = systemUserRoleMapper.selectOne(new QueryWrapper<BicycleSystemUserRole>(BicycleSystemUserRole.builder().sysUserId(systemUser.getSysUserId()).build()));
            if (bicycleSystemUserRole != null) {
                BicycleSystemRole bicycleSystemRole = systemRoleMapper.selectById(bicycleSystemUserRole.getRoleId());
                BeanUtil.copyProperties(bicycleSystemRole, bicycleSystemUserVo);
            }
            BeanUtil.copyProperties(systemUser, bicycleSystemUserVo);
            bicycleSystemUserVo.setPassword(null);
            bicycleSystemUserVoList.add(bicycleSystemUserVo);
        });
        dataGrid.setTotal(systemUserIPage.getTotal());
        dataGrid.setRows(bicycleSystemUserVoList);

        return dataGrid;
    }

    @Override
    public Message updateSysUserPassword(BicycleSystemUserPasswordDto bicycleSystemUserPasswordDto) {
        Message message = new Message();
        BicycleSystemUser systemUser = systemUserMapper.selectById(bicycleSystemUserPasswordDto.getSysUserId());
        if (!StringUtils.equals(systemUser.getPassword(), bicycleSystemUserPasswordDto.getOldPassword())) {
            message.setCode(PermissionBusinessCodeEnum.CODE_INFO_PASSWORD_FAIL.getKey());
            message.setMessage(PermissionBusinessCodeEnum.CODE_INFO_PASSWORD_FAIL.getValue());
            return message;
        }
        systemUserMapper.update(BicycleSystemUser.builder()
                .updateBy(bicycleSystemUserPasswordDto.getUpdateBy())
                .updateName(bicycleSystemUserPasswordDto.getUpdateName())
                .updateTime(new Date())
                .password(bicycleSystemUserPasswordDto.getPassword())
                .build(), new QueryWrapper<BicycleSystemUser>(BicycleSystemUser.builder().sysUserId(bicycleSystemUserPasswordDto.getSysUserId()).build()));
        return message;
    }
}
